package com.xiaopangzi.websocket.directive.intercepter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
import java.util.UUID;

/**
 * 描述:
 *
 * @author : sujinchen
 * @date : 2020/9/21
 */
public class WebSocketInterceptor implements HandshakeInterceptor {
    private Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);

    /**
     * webSocket握手的前置处理方法，
     * @param serverHttpRequest
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
            //生成一个UUID
            String uuid = UUID.randomUUID().toString().replace("-","");
            //将uuid放到websocketsession中
            //将uuid放到websocketsession中
            attributes.put("user_uuid", uuid);
            logger.info("beforeHandshake>>user_uuid：{}",uuid);
            return true;
        }
        return false;
    }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
